import axios from 'axios'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '../router'
import store from '../store'
import { httpUrl, authUrl, auth } from './config'

axios.defaults.timeout =30000;        //请求超时 
Message.duration = 1000

axios.interceptors.request.use(
    (config) => {
        if(!store.state.loadingFlag){
            store.commit('changeLoadingFlag',true)
        }
        let isLogin = config.url.includes("/oauth/token");
        let url = isLogin ? authUrl : httpUrl;
        config.baseURL = url;
        if (!isLogin) config.headers.Authorization = window.sessionStorage.getItem("token");
        NProgress.start();
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

axios.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data
        NProgress.done()
        if(store.state.loadingFlag){
            store.commit('changeLoadingFlag',false)
        }
        if (res.access_token) {
            return Promise.resolve(res);
        }
        if (res.errorCode == "0") {
            return Promise.resolve(res.bizContent);
        } else if (res.errorCode == "401") {
            Message.error("授权超时,请重新登录");
            window.location.pathname = "/login";
            return Promise.reject(res);
        } else {
            Message.error(res.errorMessage);
            return Promise.reject(res);
        }
    },
    (err) => {
        if(err && err.response) {
            switch(err.response.status){
                case 400:
                    return err.message = '请求错误(400)';
                case 401:
                    err.message = '授权超时，请重新登录(401)';
                    Message.close = ()=>{
                        router.push('/login');
                        return Promise.reject(res)
                    }
                    break;
                case 403:
                    return err.message = '账户错误，拒绝访问(403)';
                case 404:
                    return err.message = '请求地址不存在(404)';
                case 408:
                    return err.message = '请求超时(408)';
                case 500:
                    return err.message = '服务器错误';
                default :
                    return err.message = err.response.data.message || err.response.data.error_description;
            }
        } else {
            return err.message = '连接服务器失败!';
        }
        NProgress.done()
        if(store.state.loadingFlag){
            store.commit('changeLoadingFlag',false)
        }
        Message.error(err.message)
        return Promise.reject(err.response.data)
    }
)

export default axios

/**封装get */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
        params: params
        }).then(res => {
        resolve(res)
        }).catch(err => {
        reject(err)
        })
    });
}
  
/**封装post */
export function post(url, params) {
    let header = url =='/oauth/token' ? {headers: {"Content-Type": "application/x-www-form-urlencoded"},auth}:{};
    return new Promise((resolve, reject) => {
        axios.post(url, params,header).then(res => {
        resolve(res)
        }).catch(err => {
        reject(err)
        })
    });
}
  